package com.wenkang.stu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wenkang.stu.config.SmsProperties;
import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import com.wenkang.stu.mapper.AccountMapper;
import com.wenkang.stu.pojo.Account;
import com.wenkang.stu.util.IdWorker;
import com.wenkang.stu.util.NumberUtils;
import com.wenkang.stu.util.SmsUtils;
import com.wenkang.stu.vo.PageResult;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
//@EnableConfigurationProperties(SmsProperties.class)
public class AccountService {

    public static final String KEY_PREFIX = "account:code:phone:";
    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 判断用户名或手机号是否已存在
     *
     * @param data
     * @param type
     * @return
     */
    public Boolean checkData(String data, Integer type) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        switch (type) {
            case 1:
                wrapper.eq("username", "data");
                break;
            case 2:
                wrapper.eq("phone", data);
                break;
            default:
                break;
        }
        return accountMapper.selectCount(wrapper) == 0;
    }

    /**
     * 发送短信
     *
     * @param phone
     */
    public void sendVerifyCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new KangException(ExceptionEnums.PHONE_ERROR);
        }
        // 生成验证码
        String code = NumberUtils.generateCode(6);
        // 发送短信
        smsUtils.sendSms(phone, smsProperties.getSignName(), smsProperties.getVerifyCodeTemplate(), "{\"code\":\"" + code + "\"}");
        // 存储用户验证码信息
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
    }

    public void register(Account account, String code) {
        // 验证验证码是否正确
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + account.getPhone());
        if (!StringUtils.equals(cacheCode, code)) {
            throw new KangException(ExceptionEnums.CODE_ERROR);
        }
        // 加密
        account.setPassword(BCrypt.hashpw(account.getPassword(), BCrypt.gensalt()));
        accountMapper.insert(account);
    }

    public Account selectByUsername(String s) {
        if (StringUtils.isBlank(s)) {
            throw new KangException(ExceptionEnums.USERNAME_CANNOT_BE_NULL);
        }
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", s);
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null) {
            throw new KangException(ExceptionEnums.ACCOUNT_NOT_EXISTS);
        }
        return account;
    }

    /**
     * 分页查询用户
     *
     * @param page
     * @param pageSize
     * @param desc
     * @param sortBy
     * @param key
     * @return
     */
    public PageResult<Account> select(Integer page, Integer pageSize, Boolean desc, String[] sortBy, String[] key) {
        // 封装Page（分页类）
        Page<Account> pageWrapper = new Page<>(page, pageSize);
        // 查询条件
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        if (ArrayUtils.isNotEmpty(sortBy)) {
            queryWrapper.orderBy(true, desc, sortBy);
        } else {
            queryWrapper.orderByDesc("created");
        }
        if (ArrayUtils.isNotEmpty(key)) {
            queryWrapper.like("nickname", key[0]);
        }
        PageResult<Account> pageResult;
        List<Account> accountList;
        if (pageSize != -1) {
            Page<Account> accountPage = accountMapper.selectPage(pageWrapper, queryWrapper);
            accountList = accountPage.getRecords();
            pageResult = new PageResult<>(accountPage.getTotal(), accountPage.getPages(), accountList);
        } else {
            accountList = accountMapper.selectList(queryWrapper);
            pageResult = new PageResult<>((long) accountList.size(), 1L, accountList);
        }
        if (CollectionUtils.isEmpty(accountList)) {
            throw new KangException(ExceptionEnums.ACCOUNT_NOT_FIND);
        }
        return pageResult;
    }

    public void insert(Account account) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", account.getUsername()).or().eq("phone", account.getPhone());
        Account exit = accountMapper.selectOne(queryWrapper);
        if (!Objects.isNull(exit)) {
            throw new KangException(ExceptionEnums.REGISTER_ERROR);
        }
        // 创建时间
        account.setCreated(new Date());
        account.setPassword(BCrypt.hashpw(account.getPassword(), BCrypt.gensalt()));
        accountMapper.insert(account);
    }

    public void updateById(Account account) {
        int count = accountMapper.updateById(account);
        if (count != 1) {
            throw new KangException(ExceptionEnums.UPDATE_ERROR);
        }
    }

    public void deleteById(String id) {
        int count = accountMapper.deleteById(id);
        if (count != 1) {
            throw new KangException(ExceptionEnums.DELETE_ERROR);
        }
    }
}
